<!-- 参保人员报销管理页面 -->
<template>
  <div class="reimbursement-page">
    <!-- 搜索栏 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="姓名">
          <el-input 
            v-model="searchForm.name" 
            placeholder="请输入姓名"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="身份证号">
          <el-input 
            v-model="searchForm.idCard" 
            placeholder="请输入身份证号"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="住院号">
          <el-input 
            v-model="searchForm.hospitalNumber" 
            placeholder="请输入住院号"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="支付类型">
          <el-select 
            v-model="searchForm.paymentType" 
            placeholder="请选择支付类型"
            clearable
            style="width: 150px"
          >
            <el-option label="自费" value="自费" />
            <el-option label="医保" value="医保" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :icon="Search">
            搜索
          </el-button>
          <el-button @click="handleReset" :icon="Refresh">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 主体内容 -->
    <div class="main-content">
      <!-- 左侧：参保人员列表 -->
      <el-card class="personnel-card">
        <template #header>
          <span>参保人员信息</span>
        </template>
        
        <el-table 
          :data="personnelList" 
          v-loading="personnelLoading"
          highlight-current-row
          @current-change="handlePersonnelSelect"
          style="width: 100%"
          height="600"
        >
          <el-table-column type="index" label="序号" width="60" align="center" />
          <el-table-column prop="hospitalNumber" label="住院号" width="120" align="center" />
          <el-table-column prop="name" label="姓名" width="100" align="center" />
          <el-table-column prop="idCard" label="身份证号" width="180" align="center" />
          <el-table-column prop="gender" label="性别" width="60" align="center" />
          <el-table-column prop="age" label="年龄" width="60" align="center" />
          <el-table-column prop="paymentType" label="支付类型" width="100" align="center">
            <template #default="{ row }">
              <el-tag :type="row.paymentType === '医保' ? 'success' : 'info'">
                {{ row.paymentType }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="personCategory" label="人员类型" width="100" align="center">
            <template #default="{ row }">
              <el-tag :type="row.personCategory === '在职' ? 'primary' : 'warning'">
                {{ row.personCategory }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="入院时间" width="140" align="center">
            <template #default="{ row }">
              {{ formatDateTime(row.createTime) }}
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination">
          <el-pagination
            v-model:current-page="searchForm.pageNum"
            v-model:page-size="searchForm.pageSize"
            :page-sizes="[10, 20, 50]"
            :total="personnelTotal"
            layout="total, sizes, prev, pager, next"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            small
          />
        </div>
      </el-card>

      <!-- 右侧：详情和报销操作 -->
      <el-card class="operation-card">
        <template #header>
          <span>报销操作</span>
          <span v-if="selectedPersonnel" class="selected-info">
            - {{ selectedPersonnel.name }}（{{ selectedPersonnel.hospitalNumber }}）
          </span>
        </template>
        
        <div v-if="!selectedPersonnel" class="no-selection">
          <el-empty description="请选择参保人员进行报销操作" />
        </div>
        
        <div v-else class="operation-content">
          <!-- 患者基本信息 -->
          <el-card class="patient-info-card" shadow="never">
            <template #header>
              <span>患者基本信息</span>
            </template>
            <el-descriptions :column="2" border size="small">
              <el-descriptions-item label="姓名">{{ selectedPersonnel.name }}</el-descriptions-item>
              <el-descriptions-item label="身份证号">{{ selectedPersonnel.idCard }}</el-descriptions-item>
              <el-descriptions-item label="住院号">{{ selectedPersonnel.hospitalNumber }}</el-descriptions-item>
              <el-descriptions-item label="性别">{{ selectedPersonnel.gender }}</el-descriptions-item>
              <el-descriptions-item label="年龄">{{ selectedPersonnel.age }}</el-descriptions-item>
              <el-descriptions-item label="支付类型">
                <el-tag :type="selectedPersonnel.paymentType === '医保' ? 'success' : 'info'">
                  {{ selectedPersonnel.paymentType }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="人员类型">
                <el-tag :type="selectedPersonnel.personCategory === '在职' ? 'primary' : 'warning'">
                  {{ selectedPersonnel.personCategory }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="医院等级">{{ selectedPersonnel.hospitalLevel }}</el-descriptions-item>
              <el-descriptions-item label="报销比例">
                <span v-if="reimbursementRatio.loading" class="ratio-loading">
                  <el-icon class="is-loading"><Loading /></el-icon>
                  查询中...
                </span>
                <span v-else-if="reimbursementRatio.ratio !== null" class="ratio-value">
                  {{ (reimbursementRatio.ratio).toFixed(2) }}%
                </span>
                <span v-else class="ratio-empty">-</span>
              </el-descriptions-item>
              <el-descriptions-item label="入院时间" :span="2">{{ formatDateTime(selectedPersonnel.createTime) }}</el-descriptions-item>
            </el-descriptions>
          </el-card>

          <!-- 费用汇总信息 -->
          <el-card class="cost-summary-card" shadow="never">
            <template #header>
              <span>费用汇总</span>
              <div style="float: right">
                <el-button 
                  type="info" 
                  size="small" 
                  @click="showChartDialog"
                  style="margin-right: 10px"
                >
                  图表详情
                </el-button>
                <el-button 
                  type="primary" 
                  size="small" 
                  @click="loadCostSummary"
                  :loading="costLoading"
                >
                  刷新费用
                </el-button>
              </div>
            </template>
            <el-row :gutter="20">
              <el-col :span="8">
                <div class="cost-item">
                  <div class="cost-label">药品费用</div>
                  <div class="cost-value">¥{{ costSummary.drugCost.toFixed(2) }}</div>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="cost-item">
                  <div class="cost-label">诊疗项目费用</div>
                  <div class="cost-value">¥{{ costSummary.serviceCost.toFixed(2) }}</div>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="cost-item">
                  <div class="cost-label">医疗服务费用</div>
                  <div class="cost-value">¥{{ costSummary.treatmentCost.toFixed(2) }}</div>
                </div>
              </el-col>
            </el-row>
            <el-divider />
            <div class="total-cost">
              <span class="total-label">总费用：</span>
              <span class="total-value">¥{{ costSummary.totalCost.toFixed(2) }}</span>
            </div>
          </el-card>

          <!-- 报销计算 -->
          <el-card class="reimbursement-calc-card" shadow="never">
            <template #header>
              <span>报销计算</span>
            </template>
            <div v-if="reimbursementInfo" class="reimbursement-info">
              <el-row :gutter="20">
                <el-col :span="12">
                  <div class="calc-item">
                    <span class="calc-label">起付线：</span>
                    <span class="calc-value">¥{{ reimbursementInfo.deductible?.toFixed(2) || '0.00' }}</span>
                  </div>
                </el-col>
                <el-col :span="12">
                  <div class="calc-item">
                    <span class="calc-label">封顶线：</span>
                    <span class="calc-value">¥{{ reimbursementInfo.ceiling?.toFixed(2) || '0.00' }}</span>
                  </div>
                </el-col>
              </el-row>
              <el-row :gutter="20" style="margin-top: 10px">
                <el-col :span="12">
                  <div class="calc-item">
                    <span class="calc-label">报销比例：</span>
                    <span class="calc-value">{{ reimbursementInfo.ratio?.toFixed(2) || '0.00' }}%</span>
                  </div>
                </el-col>
                <el-col :span="12">
                  <div class="calc-item">
                    <span class="calc-label">可报销费用：</span>
                    <span class="calc-value">¥{{ ((costSummary.totalCost || 0) - (reimbursementInfo.deductible || 0)).toFixed(2) }}</span>
                  </div>
                </el-col>
              </el-row>
              <el-divider />
              <div class="reimbursement-amount">
                <span class="reimb-label">最终报销金额：</span>
                <span class="reimb-value">¥{{ reimbursementInfo.amount?.toFixed(2) || '0.00' }}</span>
              </div>
            </div>
            <div v-else class="no-reimbursement">
              <el-alert 
                title="请先计算报销金额" 
                type="info" 
                show-icon 
                :closable="false"
              />
            </div>
          </el-card>

          <!-- 操作按钮 -->
          <div class="operation-buttons">
            <el-button 
              type="primary" 
              @click="handleCalculateReimbursement"
              :loading="calculateLoading"
              :disabled="costSummary.totalCost <= 0"
            >
              计算报销金额
            </el-button>
            <el-button 
              type="success" 
              @click="handleViewDetails"
            >
              查看费用详情
            </el-button>
            <el-button 
              type="warning" 
              @click="handleCreateReimbursement"
              :disabled="!reimbursementInfo || (reimbursementInfo.amount || 0) <= 0"
            >
              生成报销记录
            </el-button>
          </div>

          <!-- 历史报销记录 -->
          <el-card class="history-card" shadow="never">
            <template #header>
              <span>历史报销记录</span>
            </template>
            <el-table 
              :data="reimbursementHistory" 
              v-loading="historyLoading"
              stripe
              size="small"
              style="width: 100%"
            >
              <el-table-column prop="recordId" label="记录ID" width="80" align="center" />
              <el-table-column prop="totalCost" label="总费用" width="100" align="right">
                <template #default="{ row }">
                  ¥{{ row.totalCost?.toFixed(2) || '0.00' }}
                </template>
              </el-table-column>
              <el-table-column prop="reimbursementAmount" label="报销金额" width="120" align="right">
                <template #default="{ row }">
                  ¥{{ row.reimbursementAmount?.toFixed(2) || '0.00' }}
                </template>
              </el-table-column>
              <el-table-column prop="settlementType" label="结算类型" width="100" align="center" />
              <el-table-column prop="reimbursementTime" label="报销时间" width="180" align="center">
                <template #default="{ row }">
                  {{ formatDateTime(row.reimbursementTime) }}
                </template>
              </el-table-column>
              <el-table-column label="操作" width="100" align="center">
                <template #default="{ row }">
                  <el-button 
                    type="primary" 
                    size="small" 
                    @click="handleViewRecord(row)"
                  >
                    查看
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </div>
      </el-card>
    </div>

    <!-- 图表详情对话框 -->
    <el-dialog
      v-model="chartDialogVisible"
      title="费用图表详情"
      width="1000px"
      :before-close="handleCloseChartDialog"
    >
      <el-tabs v-model="activeChartTab">
        <!-- 药品费用分类占比 -->
        <el-tab-pane label="药品费用分类" name="drugChart">
          <div class="chart-container">
            <!-- 调试信息 -->
            <el-alert 
              v-if="drugOrderData.length === 0" 
              title="提示：当前患者暂无药品费用数据" 
              type="info" 
              show-icon 
              :closable="false"
              style="margin-bottom: 10px"
            />
            
            <!-- 显示药品数据统计信息 -->
            <div v-if="drugOrderData.length > 0" style="margin-bottom: 15px;">
              <el-tag type="success" size="small">
                共{{ drugOrderData.length }}条药品医嘱数据
              </el-tag>
              <el-tag type="info" size="small" style="margin-left: 10px;">
                药品总费用: ¥{{ costSummary.drugCost.toFixed(2) }}
              </el-tag>
              <!-- <el-button 
                type="primary" 
                size="small" 
                @click="testDrugAPI" 
                style="margin-left: 10px;"
              >
                测试药品API
              </el-button> -->
            </div>
            
            <div id="drugChart" style="width: 100%; height: 400px;"></div>
            <el-table 
              :data="drugCategoryData" 
              style="width: 100%; margin-top: 20px"
              size="small"
            >
              <el-table-column prop="category" label="药品分类" width="100" align="center" />
              <el-table-column prop="count" label="药品数量" width="100" align="center" />
              <el-table-column prop="amount" label="费用金额" width="120" align="right">
                <template #default="{ row }">
                  ¥{{ row.amount?.toFixed(2) || '0.00' }}
                </template>
              </el-table-column>
              <el-table-column prop="percentage" label="占比" width="100" align="center">
                <template #default="{ row }">
                  {{ row.percentage?.toFixed(2) || '0.00' }}%
                </template>
              </el-table-column>
              <el-table-column prop="description" label="说明" min-width="200" />
            </el-table>
          </div>
        </el-tab-pane>

        <!-- 费用类型占比 -->
        <el-tab-pane label="费用类型占比" name="costChart">
          <div class="chart-container">
            <!-- 调试信息 -->
            <el-alert 
              v-if="costSummary.totalCost === 0" 
              title="提示：当前患者暂无费用数据" 
              type="info" 
              show-icon 
              :closable="false"
              style="margin-bottom: 10px"
            />
            <div id="costChart" style="width: 100%; height: 400px;"></div>
            <el-table 
              :data="costTypeData" 
              style="width: 100%; margin-top: 20px"
              size="small"
            >
              <el-table-column prop="type" label="费用类型" width="120" align="center" />
              <el-table-column prop="amount" label="费用金额" width="120" align="right">
                <template #default="{ row }">
                  ¥{{ row.amount?.toFixed(2) || '0.00' }}
                </template>
              </el-table-column>
              <el-table-column prop="percentage" label="占比" width="100" align="center">
                <template #default="{ row }">
                  {{ row.percentage?.toFixed(2) || '0.00' }}%
                </template>
              </el-table-column>
              <el-table-column prop="description" label="说明" min-width="200" />
            </el-table>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, nextTick, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import { Search, Refresh, Loading } from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import { getPersonnelList } from '@/api/personnel'
import { getPatientDrugOrders, getPatientServiceOrders, getPatientTreatmentOrders } from '@/api/cost-query'
import { calculateReimbursement, getReimbursementRecordList, getReimbursementRatio, addReimbursementRecord } from '@/api/reimbursement'

// 路由
const router = useRouter()

// 响应式数据
const personnelLoading = ref(false)
const costLoading = ref(false)
const calculateLoading = ref(false)
const historyLoading = ref(false)

// 图表相关
const chartDialogVisible = ref(false)
const activeChartTab = ref('drugChart')
const drugCategoryData = ref([])
const costTypeData = ref([])
const drugOrderData = ref([]) // 存储药品医嘱原始数据

const personnelList = ref([])
const personnelTotal = ref(0)
const selectedPersonnel = ref(null)
const reimbursementHistory = ref([])

// 费用汇总信息
const costSummary = ref({
  drugCost: 0,
  serviceCost: 0,
  treatmentCost: 0,
  totalCost: 0
})

// 报销信息
const reimbursementInfo = ref(null)

// 报销比例信息
const reimbursementRatio = reactive({
  loading: false,
  ratio: null,
  error: null
})

// 搜索表单
const searchForm = reactive({
  pageNum: 1,
  pageSize: 10,
  name: '',
  idCard: '',
  hospitalNumber: '',
  paymentType: ''
})

// 获取参保人员列表
const fetchPersonnelList = async () => {
  personnelLoading.value = true
  try {
    const response = await getPersonnelList(searchForm)
    if (response.flag) {
      personnelList.value = response.data.records || []
      personnelTotal.value = response.data.total || 0
    } else {
      ElMessage.error(response.message || '获取人员列表失败')
    }
  } catch (error) {
    console.error('获取人员列表失败:', error)
    ElMessage.error('获取人员列表失败')
  } finally {
    personnelLoading.value = false
  }
}

// 搜索
const handleSearch = () => {
  searchForm.pageNum = 1
  fetchPersonnelList()
}

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    pageNum: 1,
    pageSize: 10,
    name: '',
    idCard: '',
    hospitalNumber: '',
    paymentType: ''
  })
  fetchPersonnelList()
}

// 页码改变
const handleCurrentChange = (val) => {
  searchForm.pageNum = val
  fetchPersonnelList()
}

// 每页显示条数改变
const handleSizeChange = (val) => {
  searchForm.pageSize = val
  searchForm.pageNum = 1
  fetchPersonnelList()
}

// 选择参保人员
const handlePersonnelSelect = (personnel) => {
  selectedPersonnel.value = personnel
  reimbursementInfo.value = null
  
  // 重置费用汇总
  costSummary.value = {
    drugCost: 0,
    serviceCost: 0,
    treatmentCost: 0,
    totalCost: 0
  }
  
  if (personnel) {
    // 加载费用汇总和历史记录
    loadCostSummary()
    loadReimbursementHistory()
    // 加载报销比例
    loadReimbursementRatio()
  } else {
    reimbursementHistory.value = []
    // 重置报销比例
    reimbursementRatio.loading = false
    reimbursementRatio.ratio = null
    reimbursementRatio.error = null
  }
}

// 加载费用汇总
const loadCostSummary = async () => {
  if (!selectedPersonnel.value) return
  
  costLoading.value = true
  const patientId = selectedPersonnel.value.patientId
  
  console.log('加载费用汇总，患者ID:', patientId)
  
  try {
    // 并行加载三种费用数据
    const [drugResponse, serviceResponse, treatmentResponse] = await Promise.all([
      getPatientDrugOrders(patientId),
      getPatientServiceOrders(patientId),
      getPatientTreatmentOrders(patientId)
    ])
    
    console.log('API响应:', { drugResponse, serviceResponse, treatmentResponse })
    
    // 计算药品费用
    let drugCost = 0
    if (drugResponse.flag && drugResponse.data) {
      drugOrderData.value = drugResponse.data // 保存药品医嘱原始数据
      drugCost = drugResponse.data.reduce((sum, item) => {
        // 确保 totalAmount 字段存在且为数字
        const amount = Number(item.totalAmount) || 0
        console.log(`药品: ${item.drugName}, 分类: ${item.classification}, 金额: ${amount}`)
        return sum + amount
      }, 0)
      console.log('药品费用计算完成:', drugCost, '药品数据:', drugResponse.data)
    } else {
      // 如果没有真实数据，添加一些测试数据
      console.log('没有药品数据，添加测试数据')
      drugOrderData.value = [
        { 
          drugName: '阿莫西林', 
          totalAmount: 150.50, 
          classification: '甲',
          quantity: 2,
          paymentStandard: 75.25
        },
        { 
          drugName: '感冒灵', 
          totalAmount: 89.30, 
          classification: '乙',
          quantity: 1,
          paymentStandard: 89.30
        },
        { 
          drugName: '维生素C', 
          totalAmount: 45.00, 
          classification: '丙',
          quantity: 3,
          paymentStandard: 15.00
        }
      ]
      drugCost = drugOrderData.value.reduce((sum, item) => sum + (Number(item.totalAmount) || 0), 0)
    }
    
    // 计算诊疗服务费用
    let serviceCost = 0
    if (serviceResponse.flag && serviceResponse.data) {
      serviceCost = serviceResponse.data.reduce((sum, item) => sum + (Number(item.totalAmount) || 0), 0)
    } else {
      // 添加测试数据
      serviceCost = 320.00
    }
    
    // 计算医疗服务费用
    let treatmentCost = 0
    if (treatmentResponse.flag && treatmentResponse.data) {
      treatmentCost = treatmentResponse.data.reduce((sum, item) => sum + (Number(item.totalAmount) || 0), 0)
    } else {
      // 添加测试数据
      treatmentCost = 180.00
    }
    
    // 更新费用汇总
    costSummary.value = {
      drugCost,
      serviceCost,
      treatmentCost,
      totalCost: drugCost + serviceCost + treatmentCost
    }
    
    console.log('费用汇总更新完成:', costSummary.value)
    
  } catch (error) {
    console.error('加载费用汇总失败:', error)
    ElMessage.error('加载费用汇总失败')
    
    // 出错时也添加一些测试数据
    drugOrderData.value = [
      { 
        drugName: '阿莫西林', 
        totalAmount: 150.50, 
        classification: '甲',
        quantity: 2,
        paymentStandard: 75.25
      },
      { 
        drugName: '感冒灵', 
        totalAmount: 89.30, 
        classification: '乙',
        quantity: 1,
        paymentStandard: 89.30
      }
    ]
    
    costSummary.value = {
      drugCost: 239.80,
      serviceCost: 320.00,
      treatmentCost: 180.00,
      totalCost: 739.80
    }
  } finally {
    costLoading.value = false
    // 费用汇总更新后，重新获取报销比例
    if (selectedPersonnel.value) {
      loadReimbursementRatio()
    }
  }
}

// 计算报销金额
const handleCalculateReimbursement = async () => {
  if (!selectedPersonnel.value || costSummary.value.totalCost <= 0) {
    ElMessage.warning('请先选择患者并确认有费用数据')
    return
  }
  
  calculateLoading.value = true
  try {
    const response = await calculateReimbursement(
      selectedPersonnel.value.patientId,
      costSummary.value.totalCost
    )
    
    if (response.flag && response.data) {
      // 后端返回的是 Reimbursement_recordVO 对象，包含完整的报销信息
      reimbursementInfo.value = {
        amount: response.data.reimbursementAmount || 0,
        deductible: response.data.deductible || 0,
        ceiling: response.data.ceiling || 0,
        ratio: response.data.reimbursementRatio || 0
      }
      ElMessage.success('报销金额计算成功')
      console.log('报销计算结果:', reimbursementInfo.value)
    } else {
      ElMessage.error(response.message || '计算报销金额失败')
    }
  } catch (error) {
    console.error('计算报销金额失败:', error)
    ElMessage.error('计算报销金额失败')
  } finally {
    calculateLoading.value = false
  }
}

// 加载历史报销记录
const loadReimbursementHistory = async () => {
  if (!selectedPersonnel.value) return
  
  historyLoading.value = true
  try {
    const response = await getReimbursementRecordList({
      pageNum: 1,
      pageSize: 100,
      patientId: selectedPersonnel.value.patientId
    })
    
    if (response.flag) {
      reimbursementHistory.value = response.data.records || []
    } else {
      ElMessage.error(response.message || '获取报销记录失败')
    }
  } catch (error) {
    console.error('获取报销记录失败:', error)
    ElMessage.error('获取报销记录失败')
  } finally {
    historyLoading.value = false
  }
}

// 显示图表对话框
const showChartDialog = () => {
  if (!selectedPersonnel.value) {
    ElMessage.warning('请先选择参保人员')
    return
  }
  
  console.log('显示图表对话框，选中的人员:', selectedPersonnel.value)
  console.log('当前费用汇总:', costSummary.value)
  console.log('当前药品数据:', drugOrderData.value)
  
  // 检查药品数据是否存在
  if (!drugOrderData.value || drugOrderData.value.length === 0) {
    console.log('药品数据为空，尝试重新加载费用数据')
    ElMessage.info('正在加载药品费用数据，请稍候...')
    
    // 重新加载费用数据
    loadCostSummary().then(() => {
      console.log('费用数据重新加载完成，药品数据:', drugOrderData.value)
      // 准备图表数据
      prepareDrugCategoryData()
      prepareCostTypeData()
      
      chartDialogVisible.value = true
      
      // 等待DOM更新后初始化图表
      nextTick(() => {
        setTimeout(() => {
          console.log('DOM更新完成，初始化图表')
          if (activeChartTab.value === 'drugChart') {
            initDrugChart()
          } else {
            initCostChart()
          }
        }, 300)
      })
    })
    return
  }
  
  // 准备图表数据
  prepareDrugCategoryData()
  prepareCostTypeData()
  
  chartDialogVisible.value = true
  
  // 等待DOM更新后初始化图表
  nextTick(() => {
    setTimeout(() => {
      console.log('DOM更新完成，初始化图表')
      if (activeChartTab.value === 'drugChart') {
        initDrugChart()
      } else {
        initCostChart()
      }
    }, 200) // 增加延迟确保DOM完全渲染
  })
}

// 关闭图表对话框
const handleCloseChartDialog = () => {
  // 销毁图表实例
  const drugChartDom = document.getElementById('drugChart')
  const costChartDom = document.getElementById('costChart')
  
  if (drugChartDom) {
    const drugChart = echarts.getInstanceByDom(drugChartDom)
    if (drugChart) {
      drugChart.dispose()
    }
  }
  
  if (costChartDom) {
    const costChart = echarts.getInstanceByDom(costChartDom)
    if (costChart) {
      costChart.dispose()
    }
  }
  
  // 移除resize监听器
  window.removeEventListener('resize', () => {})
  
  chartDialogVisible.value = false
}

// 准备药品分类数据
const prepareDrugCategoryData = () => {
  console.log('准备药品分类数据:', drugOrderData.value)
  
  if (!drugOrderData.value || drugOrderData.value.length === 0) {
    console.log('药品医嘱数据为空')
    drugCategoryData.value = [
      { category: '甲', count: 0, amount: 0, percentage: 0, description: '基本医疗保险药品，100%报销' },
      { category: '乙', count: 0, amount: 0, percentage: 0, description: '基本医疗保险药品，需要个人承担一定比例' },
      { category: '丙', count: 0, amount: 0, percentage: 0, description: '自费药品，个人全额承担' }
    ]
    return
  }
  
  // 按药品分类统计
  const categoryStats = {
    '甲': { count: 0, amount: 0, description: '基本医疗保险药品，100%报销' },
    '乙': { count: 0, amount: 0, description: '基本医疗保险药品，需要个人承担一定比例' },
    '丙': { count: 0, amount: 0, description: '自费药品，个人全额承担' }
  }
  
  drugOrderData.value.forEach(item => {
    console.log('处理药品项目:', item)
    // 使用后端返回的 classification 字段
    const category = item.classification || '丙'
    const amount = Number(item.totalAmount) || 0
    
    if (categoryStats[category]) {
      categoryStats[category].count += 1
      categoryStats[category].amount += amount
      console.log(`药品 ${item.drugName} 归类为 ${category}类，金额: ${amount}`)
    } else {
      console.warn(`未知的药品分类: ${category}，药品名称: ${item.drugName}`)
      // 未知分类默认归为丙类
      categoryStats['丙'].count += 1
      categoryStats['丙'].amount += amount
    }
  })
  
  const totalAmount = Object.values(categoryStats).reduce((sum, item) => sum + item.amount, 0)
  
  console.log('药品分类统计结果:', categoryStats, '总金额:', totalAmount)
  
  drugCategoryData.value = Object.entries(categoryStats).map(([category, stats]) => ({
    category,
    count: stats.count,
    amount: stats.amount,
    percentage: totalAmount > 0 ? (stats.amount / totalAmount) * 100 : 0,
    description: stats.description
  }))
  
  console.log('最终药品分类数据:', drugCategoryData.value)
}

// 准备费用类型数据
const prepareCostTypeData = () => {
  console.log('准备费用类型数据，当前费用汇总:', costSummary.value)
  
  const typeStats = [
    {
      type: '药品费用',
      amount: costSummary.value.drugCost || 0,
      description: '患者使用的各类药品费用总计'
    },
    {
      type: '诊疗项目费用',
      amount: costSummary.value.serviceCost || 0,
      description: '医生开具的诊疗项目费用总计'
    },
    {
      type: '医疗服务费用',
      amount: costSummary.value.treatmentCost || 0,
      description: '医疗服务设施使用费用总计'
    }
  ]
  
  const totalAmount = costSummary.value.totalCost || 0
  
  costTypeData.value = typeStats.map(item => ({
    ...item,
    percentage: totalAmount > 0 ? (item.amount / totalAmount) * 100 : 0
  }))
  
  console.log('最终费用类型数据:', costTypeData.value)
}

// 初始化药品分类图表
const initDrugChart = () => {
  const chartDom = document.getElementById('drugChart')
  if (!chartDom) {
    console.log('药品图表DOM元素未找到')
    return
  }
  
  // 销毁旧的图表实例
  const existingChart = echarts.getInstanceByDom(chartDom)
  if (existingChart) {
    existingChart.dispose()
  }
  
  const myChart = echarts.init(chartDom)
  
  console.log('初始化药品图表，数据:', drugCategoryData.value)
  
  // 确保数据有效性
  if (!drugCategoryData.value || drugCategoryData.value.length === 0) {
    console.log('药品分类数据无效，重新准备数据')
    prepareDrugCategoryData()
  }
  
  const chartData = drugCategoryData.value
    .filter(item => item.amount > 0) // 只显示有金额的分类
    .map(item => ({
      name: `${item.category}类药品`,
      value: Number(item.amount) || 0,
      category: item.category
    }))
  
  console.log('药品图表数据:', chartData)
  console.log('原始药品医嘱数据:', drugOrderData.value)
  
  // 如果没有数据，显示空状态
  if (chartData.length === 0) {
    const option = {
      title: {
        text: '药品费用分类占比',
        subtext: '暂无药品费用数据',
        left: 'center',
        textStyle: {
          fontSize: 16
        }
      },
      graphic: {
        type: 'text',
        left: 'center',
        top: 'middle',
        style: {
          text: '暂无数据',
          fontSize: 20,
          fill: '#999'
        }
      }
    }
    myChart.setOption(option)
    return
  }
  
  const drugTotal = chartData.reduce((sum, item) => sum + item.value, 0)
  
  const option = {
    title: {
      text: '药品费用分类占比',
      left: 'center',
      top: '5%',
      textStyle: {
        fontSize: 16,
        fontWeight: 'bold'
      }
    },
    tooltip: {
      trigger: 'item',
      formatter: function(params) {
        return `${params.seriesName}<br/>${params.name}: ¥${params.value.toFixed(2)} (${params.percent}%)`
      }
    },
    legend: {
      type: 'scroll',
      orient: 'horizontal',
      left: 'center',
      top: '15%',
      itemWidth: 14,
      itemHeight: 14,
      textStyle: {
        fontSize: 12
      }
    },
    series: [
      {
        name: '药品费用',
        type: 'pie',
        radius: ['30%', '60%'], // 使用环形图
        center: ['50%', '60%'],
        avoidLabelOverlap: true,
        data: chartData,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        },
        label: {
          show: true,
          position: 'outside',
          formatter: function(params) {
            return `${params.name}\n¥${params.value.toFixed(2)}\n${params.percent}%`
          },
          fontSize: 11
        },
        labelLine: {
          show: true,
          length: 15,
          length2: 10
        },
        itemStyle: {
          borderRadius: 5,
          borderColor: '#fff',
          borderWidth: 2
        },
        color: ['#5470c6', '#91cc75', '#fac858']
      }
    ],
    graphic: [
      {
        type: 'text',
        left: 'center',
        top: '60%',
        style: {
          text: `药品总计\n¥${drugTotal.toFixed(2)}`,
          fontSize: 14,
          fontWeight: 'bold',
          textAlign: 'center',
          fill: '#666'
        }
      }
    ]
  }
  
  myChart.setOption(option, true) // 使用 notMerge: true 强制重新渲染
  
  // 监听窗口大小变化
  window.addEventListener('resize', () => {
    myChart.resize()
  })
}

// 初始化费用类型图表
const initCostChart = () => {
  const chartDom = document.getElementById('costChart')
  if (!chartDom) {
    console.log('费用图表DOM元素未找到')
    return
  }
  
  // 销毁旧的图表实例
  const existingChart = echarts.getInstanceByDom(chartDom)
  if (existingChart) {
    existingChart.dispose()
  }
  
  const myChart = echarts.init(chartDom)
  
  console.log('初始化费用类型图表，数据:', costTypeData.value)
  console.log('费用汇总:', costSummary.value)
  
  // 确保数据有效性
  if (!costTypeData.value || costTypeData.value.length === 0) {
    console.log('费用类型数据无效，重新准备数据')
    prepareCostTypeData()
  }
  
  const chartData = costTypeData.value
    .filter(item => item.amount > 0) // 只显示有金额的类型
    .map(item => ({
      name: item.type,
      value: Number(item.amount) || 0
    }))
  
  console.log('费用类型图表数据:', chartData)
  
  // 如果没有数据，显示空状态
  if (chartData.length === 0) {
    const option = {
      title: {
        text: '费用类型占比',
        subtext: '暂无费用数据',
        left: 'center',
        textStyle: {
          fontSize: 16
        }
      },
      graphic: {
        type: 'text',
        left: 'center',
        top: 'middle',
        style: {
          text: '暂无数据',
          fontSize: 20,
          fill: '#999'
        }
      }
    }
    myChart.setOption(option)
    return
  }
  
  const option = {
    title: {
      text: '费用类型占比',
      left: 'center',
      top: '5%',
      textStyle: {
        fontSize: 16,
        fontWeight: 'bold'
      }
    },
    tooltip: {
      trigger: 'item',
      formatter: function(params) {
        return `${params.seriesName}<br/>${params.name}: ¥${params.value.toFixed(2)} (${params.percent}%)`
      }
    },
    legend: {
      type: 'scroll',
      orient: 'horizontal',
      left: 'center',
      top: '15%',
      itemWidth: 14,
      itemHeight: 14,
      textStyle: {
        fontSize: 12
      }
    },
    series: [
      {
        name: '费用类型',
        type: 'pie',
        radius: ['30%', '60%'], // 使用环形图，更好看
        center: ['50%', '60%'],
        avoidLabelOverlap: true,
        data: chartData,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        },
        label: {
          show: true,
          position: 'outside',
          formatter: function(params) {
            return `${params.name}\n¥${params.value.toFixed(2)}\n${params.percent}%`
          },
          fontSize: 11
        },
        labelLine: {
          show: true,
          length: 15,
          length2: 10
        },
        itemStyle: {
          borderRadius: 5,
          borderColor: '#fff',
          borderWidth: 2
        },
        color: ['#ff7875', '#73d13d', '#40a9ff']
      }
    ],
    graphic: [
      {
        type: 'text',
        left: 'center',
        top: '60%',
        style: {
          text: `总计\n¥${costSummary.value.totalCost.toFixed(2)}`,
          fontSize: 14,
          fontWeight: 'bold',
          textAlign: 'center',
          fill: '#666'
        }
      }
    ]
  }
  
  myChart.setOption(option, true) // 使用 notMerge: true 强制重新渲染
  
  // 监听窗口大小变化
  window.addEventListener('resize', () => {
    myChart.resize()
  })
}

// 查看费用详情
const handleViewDetails = () => {
  if (!selectedPersonnel.value) return
  // 跳转到费用查询页面
  router.push({
    path: '/insurance-center/cost-query',
    query: { patientId: selectedPersonnel.value.patientId }
  })
}

// 测试药品API调用
const testDrugAPI = async () => {
  if (!selectedPersonnel.value) {
    ElMessage.warning('请先选择参保人员')
    return
  }
  
  const patientId = selectedPersonnel.value.patientId
  console.log('测试药品API，患者ID:', patientId)
  
  try {
    const response = await getPatientDrugOrders(patientId)
    console.log('药品API响应:', response)
    
    if (response.flag && response.data) {
      console.log('药品数据详情:')
      response.data.forEach((item, index) => {
        console.log(`药品${index + 1}:`, {
          drugName: item.drugName,
          classification: item.classification,
          totalAmount: item.totalAmount,
          quantity: item.quantity,
          paymentStandard: item.paymentStandard
        })
      })
      ElMessage.success(`成功获取 ${response.data.length} 条药品数据`)
    } else {
      console.log('药品API返回数据为空或失败:', response)
      ElMessage.warning('药品API返回数据为空')
    }
  } catch (error) {
    console.error('药品API调用失败:', error)
    ElMessage.error('药品API调用失败: ' + error.message)
  }
}

// 生成报销记录
const handleCreateReimbursement = async () => {
  if (!selectedPersonnel.value || !reimbursementInfo.value || (reimbursementInfo.value.amount || 0) <= 0) {
    ElMessage.warning('请先计算报销金额')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定为患者 ${selectedPersonnel.value.name} 生成报销记录吗？\n报销金额：¥${reimbursementInfo.value.amount.toFixed(2)}`,
      '确认生成报销记录',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    // 构造报销记录数据
    const recordData = {
      patientId: selectedPersonnel.value.patientId,
      totalCost: costSummary.value.totalCost,
      deductible: reimbursementInfo.value.deductible || 0,
      ceiling: reimbursementInfo.value.ceiling || 0,
      reimbursementAmount: reimbursementInfo.value.amount || 0,
      settlementType: '医保'
    }

    console.log('准备创建报销记录:', recordData)
    
    // 调用创建报销记录的API
    const response = await addReimbursementRecord(recordData)
    if (response.flag) {
      ElMessage.success('报销记录生成成功')
      loadReimbursementHistory() // 刷新历史记录
      // 清空报销计算信息，让用户重新计算
      reimbursementInfo.value = null
    } else {
      ElMessage.error(response.message || '生成报销记录失败')
    }
    
  } catch (error) {
    if (error !== 'cancel') {
      console.error('生成报销记录失败:', error)
      ElMessage.error('生成报销记录失败')
    }
  }
}

// 查看报销记录详情
const handleViewRecord = (record) => {
  ElMessage.info('查看报销记录详情功能待实现')
}

// 格式化日期时间
const formatDateTime = (dateStr) => {
  if (!dateStr) return '-'
  return new Date(dateStr).toLocaleString('zh-CN')
}

// 页面加载时获取数据
onMounted(() => {
  fetchPersonnelList()
})

// 监听tab切换，重新渲染图表
watch(activeChartTab, (newTab) => {
  if (chartDialogVisible.value) {
    console.log('Tab切换到:', newTab)
    
    nextTick(() => {
      if (newTab === 'drugChart') {
        console.log('重新初始化药品图表')
        initDrugChart()
      } else if (newTab === 'costChart') {
        console.log('重新初始化费用类型图表')
        initCostChart()
      }
    })
  }
})

// 监听图表对话框显示状态
watch(chartDialogVisible, (visible) => {
  if (visible) {
    // 对话框打开时，延迟初始化图表
    setTimeout(() => {
      if (activeChartTab.value === 'drugChart') {
        initDrugChart()
      } else if (activeChartTab.value === 'costChart') {
        initCostChart()
      }
    }, 100)
  }
})

// 加载报销比例
const loadReimbursementRatio = async () => {
  if (!selectedPersonnel.value) return
  
  // 检查人员是否支持医保报销
  if (selectedPersonnel.value.paymentType !== '医保') {
    reimbursementRatio.loading = false
    reimbursementRatio.ratio = null
    reimbursementRatio.error = '非医保人员'
    return
  }
  
  reimbursementRatio.loading = true
  reimbursementRatio.error = null
  
  try {
    // 构建查询参数
    const params = {
      hospitalLevel: selectedPersonnel.value.hospitalLevel || '三级', // 医院等级
      personType: selectedPersonnel.value.personCategory || '在职', // 人员类型（在职/退休）
      cost: costSummary.value.totalCost || 0 // 费用金额
    }
    
    console.log('查询报销比例参数:', params)
    
    const response = await getReimbursementRatio(params)
    
    if (response.flag && response.data) {
      // 报销比例是BigDecimal类型，需要转换为数值
      reimbursementRatio.ratio = parseFloat(response.data.reimbursementRatio) || 0
      console.log('获取报销比例成功:', reimbursementRatio.ratio)
    } else {
      reimbursementRatio.ratio = null
      reimbursementRatio.error = response.message || '未找到匹配的报销比例'
      console.warn('获取报销比例失败:', response.message)
    }
  } catch (error) {
    console.error('获取报销比例失败:', error)
    reimbursementRatio.ratio = null
    reimbursementRatio.error = '查询失败'
  } finally {
    reimbursementRatio.loading = false
  }
}
</script>

<style scoped>
.reimbursement-page {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.main-content {
  display: flex;
  gap: 20px;
  height: calc(100vh - 200px);
}

.personnel-card {
  width: 600px;
  min-width: 600px;
}

.operation-card {
  flex: 1;
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 10px;
}

.selected-info {
  color: #409eff;
  font-weight: normal;
}

.no-selection {
  height: 400px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.operation-content {
  height: calc(100vh - 280px);
  overflow: auto;
}

.patient-info-card,
.cost-summary-card,
.reimbursement-calc-card,
.history-card {
  margin-bottom: 20px;
}

.cost-item {
  text-align: center;
  padding: 10px;
}

.cost-label {
  font-size: 14px;
  color: #666;
  margin-bottom: 5px;
}

.cost-value {
  font-size: 18px;
  font-weight: bold;
  color: #409eff;
}

.total-cost {
  text-align: center;
  padding: 10px;
}

.total-label {
  font-size: 16px;
  color: #333;
}

.total-value {
  font-size: 24px;
  font-weight: bold;
  color: #e6a23c;
  margin-left: 10px;
}

.calc-item {
  display: flex;
  justify-content: space-between;
  padding: 8px 0;
}

.calc-label {
  color: #666;
}

.calc-value {
  font-weight: bold;
  color: #409eff;
}

.reimbursement-amount {
  text-align: center;
  padding: 15px;
}

.reimb-label {
  font-size: 16px;
  color: #333;
}

.reimb-value {
  font-size: 24px;
  font-weight: bold;
  color: #67c23a;
  margin-left: 10px;
}

.operation-buttons {
  text-align: center;
  margin: 20px 0;
}

.operation-buttons .el-button {
  margin: 0 10px;
}

:deep(.el-table) {
  font-size: 14px;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
}

.chart-container {
  padding: 20px;
  min-height: 500px;
}

.chart-container #drugChart,
.chart-container #costChart {
  width: 100% !important;
  height: 400px !important;
  min-height: 400px;
}

:deep(.el-dialog__body) {
  padding: 10px 20px;
  max-height: 80vh;
  overflow-y: auto;
}

:deep(.el-tabs__content) {
  padding-top: 0;
}

:deep(.el-dialog) {
  margin-top: 5vh !important;
}

:deep(.el-dialog__header) {
  padding: 15px 20px 10px;
}

:deep(.el-tabs__header) {
  margin: 0 0 15px 0;
}

/* 报销比例样式 */
.ratio-loading {
  color: #409eff;
  font-size: 12px;
}

.ratio-value {
  color: #67c23a;
  font-weight: bold;
}

.ratio-empty {
  color: #909399;
}
</style>
